﻿using HandmadeShop.BusinessLogic.Entities;
using HandmadeShop.BusinessLogic.Repositories;
using HandmadeShop.BusinessLogic.Utilities;
using HandmadeShop.Database;
using System;
using System.Linq;
using System.Transactions;

namespace HandmadeShop.BusinessLogic
{
    public class AccountBL : BaseBL
    {
        private GenericRepository<Account> accountRepository;

        public AccountBL()
            : this(null)
        {
        }

        public AccountBL(HandmadeShopEntities context)
            : base(context)
        {            
            this.Init();
        }

        private void Init()
        {
            this.accountRepository = this.unitOfWork.AccountRepository;
        }

        public User GetById(Guid id)
        {
            if (id == Guid.Empty) return null;

            var account = this.accountRepository.GetByID(id);
            var rs = new User
            {
                Id = account.Id,
                Email = account.Email,
                Role = account.Role
            };

            return rs;
        }

        public User Login(string email, string password)
        {
            password = Helper.Instance.Encrypt(password);
            var account = this.accountRepository.Get(p => p.Email.Equals(email) && p.Password.Equals(password)).FirstOrDefault();
            if (account == null) return null;

            User user = new User
            {
                Id = account.Id,
                Email = account.Email,
                Role = account.Role
            };

            return user;
        }

        public void Register(string email, string password, string role = "User")
        {
            password = Helper.Instance.Encrypt(password);

            var id = Guid.NewGuid();
            var now = DateTime.Now;

            using (TransactionScope transaction = new TransactionScope())
            {
                var account = new Account()
                {
                    Id = id,
                    Email = email,
                    Password = password,
                    Phone = "",
                    CreatedBy = id,
                    CreatedDate = now,
                    ModifiedBy = id,
                    ModifiedDate = now,
                    Role = role
                };

                this.accountRepository.Insert(account);
                this.accountRepository.Save();

                transaction.Complete();
            }
        }
    }
}
